// 患者登录页面组件


import { Button, Form, Input, Checkbox, Toast } from 'antd-mobile'
import { useState } from 'react'
import type { FormProps } from 'antd-mobile'
import { useNavigate } from "react-router-dom";
import { postHttp } from '../../request/api';
import JSEncrypt from 'jsencrypt';

// 类型定义
interface LoginForm {
    email: string
    password: string
}

interface LoginResponse {
    status: string;
    message: string;
    result: {
        userId: number;
        sessionId: string;
        nickName: string;
        userName: string;
        jiGuangPwd: string;
        headPic: string;
        sex: number;
        age: number;
        height: number;
        weight: number;
        email: string;
        whetherBingWeChat: number;
        invitationCode: string;
        faceFlag: number;
    };
}

export default function PatientLoginPage() {
    const [form] = Form.useForm<LoginForm>()
    const [loading, setLoading] = useState(false)
    const navigator = useNavigate()

    const publicKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`;

    const encryptedData = (publicKey: string, data: string) => {
        const encryptor = new JSEncrypt();
        encryptor.setPublicKey(publicKey);
        return encryptor.encrypt(data);
    };

    // 提交处理
    const handleSubmit: FormProps['onFinish'] = async (values) => {
        setLoading(true);
        try {
            const value = { 
                email: values.email, 
                pwd: encryptedData(publicKey, values.password) 
            };
            
            const response = await postHttp('/health/user/v1/login', value);
            const res = response.data as LoginResponse;
            
            if (res.status === '0000') {
                // 存储用户信息
                localStorage.setItem('userInfo', JSON.stringify({
                    userId: res.result.userId,
                    sessionId: res.result.sessionId,
                    nickName: res.result.nickName,
                    userName: res.result.userName,
                    jiGuangPwd: res.result.jiGuangPwd,
                    headPic: res.result.headPic,
                    sex: res.result.sex,
                    age: res.result.age,
                    height: res.result.height,
                    weight: res.result.weight,
                    email: res.result.email,
                    whetherBingWeChat: res.result.whetherBingWeChat,
                    invitationCode: res.result.invitationCode,
                    faceFlag: res.result.faceFlag
                }));

                // 登录成功后跳转到首页
                navigator('/home');
            } else {
                Toast.show({
                    content: res.message || '登录失败',
                    position: 'center',
                });
            }
        } catch (error) {
            Toast.show({
                content: '登录失败，请稍后重试',
                position: 'center',
            });
            console.error('Login error:', error);
        } finally {
            setLoading(false);
        }
    }

    return (
        <div style={{ padding: 24 }}>
            <h1 style={{ textAlign: 'center', margin: '30px 0' }}>
                患者登录
            </h1>
            <Form
                form={form}
                onFinish={handleSubmit}
                footer={
                    <Button
                        block
                        type="submit"
                        color="primary"
                        loading={loading}
                        shape="rounded"
                        size="large"
                    >
                        登录
                    </Button>
                }
            >
                {/* 邮箱输入 */}
                <Form.Item
                    name="email"
                    rules={[
                        { required: true, message: '请输入邮箱' },
                        { type: 'email', message: '邮箱格式不正确' }
                    ]}
                >
                    <Input
                        placeholder="请输入邮箱"
                        clearable
                        type="email"
                    />
                </Form.Item>

                {/* 密码输入 */}
                <Form.Item
                    name="password"
                    rules={[
                        { required: true, message: '请输入密码' },
                        { min: 6, message: '密码至少6位' }
                    ]}
                >
                    <Input
                        placeholder="请输入密码"
                        clearable
                        type="password"
                    />
                </Form.Item>

                {/* 记住我 & 忘记密码 */}
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    margin: '16px 0'
                }}>
                    <Form.Item name="remember" noStyle>
                        <Checkbox>记住我</Checkbox>
                    </Form.Item>

                    <a
                        href="#/forgot-password"
                        style={{ color: '#1677ff', fontSize: 14 }}
                    >
                        忘记密码？
                    </a>
                </div>
            </Form>
        </div>
    )
}
